"""
需求相关数据库索引初始化脚本
"""
import logging
from motor.motor_asyncio import AsyncIOMotorDatabase  # pyright: ignore[reportMissingImports]

logger = logging.getLogger(__name__)


async def init_requirement_indexes(db: AsyncIOMotorDatabase):
    """
    初始化需求相关的数据库索引
    
    Args:
        db: 数据库连接
    """
    try:
        # 1. 需求集合索引
        # 项目ID索引（最常用的筛选条件）
        try:
            await db.requirements.create_index(
                [("project_id", 1)],
                name="project_id_idx"
            )
            logger.info("创建索引: requirements.project_id_idx")
        except Exception as e:
            logger.debug(f"创建索引失败（可能已存在）: {e}")
        
        # 状态索引
        try:
            await db.requirements.create_index(
                [("status", 1)],
                name="status_idx"
            )
            logger.info("创建索引: requirements.status_idx")
        except Exception as e:
            logger.debug(f"创建索引失败（可能已存在）: {e}")
        
        # 负责人索引
        try:
            await db.requirements.create_index(
                [("assignee_id", 1)],
                name="assignee_id_idx"
            )
            logger.info("创建索引: requirements.assignee_id_idx")
        except Exception as e:
            logger.debug(f"创建索引失败（可能已存在）: {e}")
        
        # 报告人索引
        try:
            await db.requirements.create_index(
                [("reporter_id", 1)],
                name="reporter_id_idx"
            )
            logger.info("创建索引: requirements.reporter_id_idx")
        except Exception as e:
            logger.debug(f"创建索引失败（可能已存在）: {e}")
        
        # 创建时间索引（用于排序）
        try:
            await db.requirements.create_index(
                [("created_at", -1)],
                name="created_at_idx"
            )
            logger.info("创建索引: requirements.created_at_idx")
        except Exception as e:
            logger.debug(f"创建索引失败（可能已存在）: {e}")
        
        # 更新时间索引（用于排序）
        try:
            await db.requirements.create_index(
                [("updated_at", -1)],
                name="updated_at_idx"
            )
            logger.info("创建索引: requirements.updated_at_idx")
        except Exception as e:
            logger.debug(f"创建索引失败（可能已存在）: {e}")
        
        # 父需求ID索引（用于树形结构）
        try:
            await db.requirements.create_index(
                [("parent_id", 1)],
                name="parent_id_idx"
            )
            logger.info("创建索引: requirements.parent_id_idx")
        except Exception as e:
            logger.debug(f"创建索引失败（可能已存在）: {e}")
        
        # 优先级索引
        try:
            await db.requirements.create_index(
                [("priority", 1)],
                name="priority_idx"
            )
            logger.info("创建索引: requirements.priority_idx")
        except Exception as e:
            logger.debug(f"创建索引失败（可能已存在）: {e}")
        
        # 需求类型索引
        try:
            await db.requirements.create_index(
                [("requirement_type", 1)],
                name="requirement_type_idx"
            )
            logger.info("创建索引: requirements.requirement_type_idx")
        except Exception as e:
            logger.debug(f"创建索引失败（可能已存在）: {e}")
        
        # 复合索引：项目ID + 状态（常用组合查询）
        try:
            await db.requirements.create_index(
                [("project_id", 1), ("status", 1)],
                name="project_status_idx"
            )
            logger.info("创建索引: requirements.project_status_idx")
        except Exception as e:
            logger.debug(f"创建索引失败（可能已存在）: {e}")
        
        # 复合索引：项目ID + 创建时间（常用组合查询和排序）
        try:
            await db.requirements.create_index(
                [("project_id", 1), ("created_at", -1)],
                name="project_created_at_idx"
            )
            logger.info("创建索引: requirements.project_created_at_idx")
        except Exception as e:
            logger.debug(f"创建索引失败（可能已存在）: {e}")
        
        # 复合索引：负责人 + 状态
        try:
            await db.requirements.create_index(
                [("assignee_id", 1), ("status", 1)],
                name="assignee_status_idx"
            )
            logger.info("创建索引: requirements.assignee_status_idx")
        except Exception as e:
            logger.debug(f"创建索引失败（可能已存在）: {e}")
        
        # 2. 版本需求关联表索引（如果还没有）
        try:
            await db.version_requirement_relations.create_index(
                [("requirement_id", 1)],
                name="requirement_id_idx"
            )
            logger.info("创建索引: version_requirement_relations.requirement_id_idx")
        except Exception as e:
            logger.debug(f"创建索引失败（可能已存在）: {e}")
        
        logger.info("需求相关索引初始化完成")
        
    except Exception as e:
        logger.error(f"初始化需求索引失败: {str(e)}", exc_info=True)

